# Reksio - Memory Map Editor
# Copyright (C) 2023 CERN
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# In applying this licence, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization or
# submit itself to any jurisdiction.

import reksio


def file_changed(main_window, attr_index):
    if not main_window.getPromptSubmap():
        main_window.setPromptSubmap(True)
        nodes_model = main_window.getNodesModel()
        attr_model = attr_index.getAttributesModel()
        attr = attr_model.getAttribute(attr_index)
        node = attr_model.getParentMemoryNode()
        memory_map_node = node.getChildByType("memory-map")

        if memory_map_node and memory_map_node.editable:
            node_index = nodes_model.getIndex(memory_map_node)
            answer = reksio.popup_question("Submap map file was modified externally.",
                                           f"{attr.value} has been modified by an external program.\n "
                                           f"Do you want to reload all maps from disk ?")
            if answer == answer.Yes:
                undo_stack = main_window.getUndoStack()
                undo_stack.resetClean()
                main_window.reload()
            else:
                reksio.dummyCommand(node_index, f"Submap file {attr.value} changed externally and user chose not to load "
                                                f"changes. Save to override all external changes.")

        main_window.setPromptSubmap(False)


def root_file_changed(main_window):
    if not main_window.getPromptMainmap():
        main_window.setPromptMainmap(True)
        answer = reksio.popup_question("Memory map file was modified externally.",
                                       "This file has been modified by an external program.\n Do you want to reload it ?")

        if answer == answer.Yes:
            undo_stack = main_window.getUndoStack()
            undo_stack.resetClean()
            main_window.reload()
        else:
            nodes = main_window.getNodesModel()
            reksio.dummyCommand(nodes.getIndex(nodes.getRoot()),
                                "Main memory map changed externally and user chose not to load changes. Save to override "
                                "external changes.")
        main_window.setPromptMainmap(False)
